package com.notice.config;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.LogFactory;
import com.notice.rule.LogNoticeRuleFactory;
import com.notice.rule.print.LogNoticeMsgFactory;
import com.notice.util.DingRobot;
import com.notice.util.ObjectUtils;


/**
 * 钉钉信息通知,集中警告处理，不然会进入死循环一直打印发送失败，一直打印错误信息
 *
 * @Author dzl
 * @Date 2022/1/4 3:01 下午
 */
public class DingNoticeAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

    @Override
    protected void append(ILoggingEvent event) {
        try {
            //日志通知配置信息
            if (LogSpringContent.isNoStartSuccess()) {
                LogFactory.get().warn("日志报警还没有加载好");
                return;
            }
            String error = event.getFormattedMessage();
            String exceptionClassName = ObjectUtils.nvl(event.getThrowableProxy(), () -> event.getThrowableProxy().getClassName(), "");
            //1、过滤判断
            if (LogNoticeRuleFactory.matchRule(exceptionClassName, error)) {
                //2、消息加工
                String print = LogNoticeMsgFactory.print(event);
                if (StrUtil.isBlank(print)) {
                    return;
                }
                String assemble = LogSpringContent.getLogDingInfo().getFinalHeaderMsg().concat(print);
                //3、发送通知
                DingRobot.sendTextMessage(assemble);
            }
        } catch (Exception e) {
            LogFactory.get().warn(e);
            /*异常不在向上抛，不然会出现死循环*/
        }
    }
}
